package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.INewsScanService;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
public class MediaListener {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private INewsScanService scanService;

    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                RQueue<String> rQueue = redissonClient.getBlockingQueue("article-publish");
                RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(rQueue);
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);
                try {
                    while (true) {
                        String poll = rQueue.poll();
                        if (!StringUtils.isEmpty(poll) && !poll.equals("init")) {
                            WmNews news = JSON.parseObject(poll, WmNews.class);
                            scanService.scanNow(news);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
